/*
目前这个机构只管理一个FPGA电源，不存在多个FPGA通信分别关断开。
公司不会有这种先进需求的。

电源管理和FPGA通信耦合在一起也甭管了，反正3年之内我应该不会动这个电源管理
2021.7.28 by Menglong Wu
*/
#include "port.h"
#include "fpga-common.h"
#include "fpga-private.h"
#include "interface/protocal-otdr.h"

#include <stdio.h>
#include <unistd.h>
#include <sys/prctl.h>

int watchdog = 0;


void *thread_detect_busy(void *ptr)
{
    struct fpga_dev *dev = (struct fpga_dev *)ptr;

#define NOW_NULL           (0)
#define NOW_FPGA_POWER_OFF (1)
#define NOW_FPGA_POWER_ON  (2)
    int status = NOW_NULL;
    prctl(PR_SET_NAME, __FUNCTION__);
    while (1) {
	if (WDG_IS_TIMEOUT()) {
	    // printf("do power down...\r\n");
	    if (status != NOW_FPGA_POWER_OFF) {
		// printf("do power down f\r\n");

		fpga_if_suspend(dev);
		status = NOW_FPGA_POWER_OFF;
	    }
	}
	else {
	    // printf("do power up...\r\n");
	    if (status != NOW_FPGA_POWER_ON) {
		// printf("do power up f\r\n");
		fpga_if_resume(dev);
		status = NOW_FPGA_POWER_ON;
	    }
	}
	sleep(1);
	wdt_tick();
    }
    return 0;
}

void low_power_task()
{
    static struct fpga_dev dev;
    struct fpga_if        *pmif;

    // env_lowpower_thread应该是“字符串类型”不是“整形”
    // char *ifname = env_lowpower_thread ? env_lowpower_thread : "this-pm";
    char *ifname = "this-pm";

    pmif = fpga_if_append(ifname);
    if (!pmif) {
	printf("通用电源管理接口“%s”未注册，线程“thread_detect_busy”不创建\r\n", ifname);
	return;
    }
    dev.interface = pmif;
    static pthread_t g_readtimeout;

    pthread_create(&g_readtimeout, NULL, thread_detect_busy, &dev);
}

/*
临时接通FPGA电源，电源接通才能工作

接口写的很难看，为什么电源管理我要关联到fpga_if上为什么不定义一个

struct fpga_if
{
    ...
    struct pm_dev *pm;
}

struct pm_dev
{
    void *private_data;  --> struct fpga_dev;
    struct pm_if *interface;
}
struct pm_if
{
    int (*pfun_suspend)(struct pm_dev *dev);
    int (*pfun_resume)(struct pm_dev *dev);
}
*/

int fpga_power_up()
{
    struct fpga_dev dev;
    struct fpga_if *pmif;

    // char *ifname = env_lowpower_thread ? env_lowpower_thread : "this-pm";
    char *ifname = "this-pm";

    pmif = fpga_if_append(ifname);
    if (!pmif) {
	printf("通用电源管理接口“%s”未注册，线程“thread_detect_busy”不创建\r\n", ifname);
	return 0;
    }
    dev.interface = pmif;
    fpga_if_resume(&dev);
    return 0;
}

static void __attribute__((constructor(INIT_THREAD))) _load_env()
{
    low_power_task();
}
